<?php

class CheckOutController extends FController {
	public $layout='//layouts/main';
	public $defaultAction = "Index";
	
	public function init(){
		Yii::app()->theme = 'frontend';
		parent::init();
	}
	
	public function actionPayment($id) {
		$carts = Carts::model()->findByPk($id);
		
		$product = Products::model()->findByPk($carts->product_id);
		$this->render('payment', array(
			'carts'=>$carts,
			'product'=>$product,
		));
	}
	public function actionIndex() {
		
		$model = new CheckOutForm();
		if(!empty($_POST) && !empty($_POST['CheckOutForm']['payment'])  && $_POST['CheckOutForm']['payment'] == "Paypal")
		{
			
			$model = new CheckOutForm('p');
		}
		$pid = Yii::app()->request->getParam('pid',null);
		$product = array();
		// dump(Yii::app()->session['listcart'],false);
		$cart = array();
		// if(Yii::app()->session['cart'] == null){
			
			// $this->redirect(Yii::app()->createUrl('/home'));
		// }
		
		if($pid != null && !empty(Yii::app()->session['listcart'][$pid])){
			$product = Products::model()->findByPk(Yii::app()->session['listcart'][$pid]['product_id']);
			$cart = Yii::app()->session['listcart'][$pid];
		}else{
			$cart = Yii::app()->session['cart'];
			$product = Products::model()->findByPk(Yii::app()->session['cart']['product_id']);
		}
		if(empty($product)) $this->redirect(Yii::app()->createUrl('/home'));
		if (isset($_POST) && isset($_POST['CheckOutForm'])) {
			$model->attributes = $_POST['CheckOutForm'];
			$model->state = $_POST['CheckOutForm']['state'];
			$model->emailPaypal = $_POST['CheckOutForm']['emailPaypal'];
			// dump($_POST,false);
			// dump($model->attributes);
			if ($model->validate()) {
				$carts = new Carts;
				$carts->attributes = $model->attributes;
				$pending = Configs::model()->findByAttributes(array('type'=>0));
				$carts->config_id = $pending->id;
				$carts->product_id = $cart['product_id'];
				$carts->emailPaypal = $model->emailPaypal;
				$carts->quantity =  $cart['quantity'];
				$carts->price =  $product->price;
				$carts->created =  time();
				$carts->options =  $cart['options'];
				// dump($carts->attributes,false);
				if($carts->save()){
					
					if($model->payment != "Paypal"){
						$this->redirect('/home');
					}
					Yii::app()->session['cart'] = null;
					Yii::app()->user->setFlash('success', "Validate infomation successfully!");
					$this->redirect(Yii::app()->createUrl('/products/checkOut/payment',array('id'=>$carts->id)));
					
				}
				// dump($carts->attributes,false);
			}else{
				// dump($model->validate());
			}
		}
		// $emailConfig = Configs::model()->findByAttributes(array('type'=>1));
		$this->render('index', array(
			'model'		=> $model,
			'cart'		=> $cart,
			'product'		=> $product,
			
			'arrStatus'				=> CheckOutForm::getState(),
			'arrTermsConditions'	=> CheckOutForm::getTermsConditions()
		));
	}
}